package com.example.admin.controller;

import com.example.admin.service.CategoryService;
import com.example.xo.common.Result;
import com.example.xo.pojo.Category;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author YangJiaHao
 */
@RestController
@Slf4j
@RequestMapping("category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping("add")
    public Result add(@RequestBody Category category) {
        if (category.getCategoryName().length() > 20) {
            log.info("分类{}字符个数超过20", category.getCategoryName());
            return Result.error();
        }
        boolean result = categoryService.add(category);
        if (result==false){
            return Result.error();
        }
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        List<Category> list = categoryService.findAll();
        return Result.success(list);
    }

    @GetMapping("{id}")
    public Result findById(@PathVariable String id) {
        Category category = categoryService.findById(id);
        if (category==null || category.getDeleted()!=null){
            return Result.error();
        }
        return Result.success(category);
    }

    @DeleteMapping ("{id}")
    public Result delete(@PathVariable String id){
        if (categoryService.findById(id)==null || categoryService.findById(id).getDeleted()!=null){
            return Result.error();
        }
        categoryService.delete(id);
        return Result.success();
    }

    @PutMapping("update")
    public Result update(@RequestBody Category category){
        boolean result = categoryService.update(category);
        if (result==false){
            return Result.error();
        }
        return Result.success();
    }
}
